<script setup>
import { reactive, computed, ref, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";

let router = useRouter();
let route = useRoute();

let data = reactive({ drawer: false });

let menuTop = ref();
let menuLeft = ref();
let contextMenuVisible = ref(false);

// 获取路由列表
const routes = computed(() => router.getRoutes());

// 获取路由的 path 和 meta.label
const routePathsAndLabels = computed(() => {
  return routes.value
    .map((item) => ({
      path: item.path,
      label: item.meta.label,
      isActive: item.path === route.path, // 默认不激活
    }));
});

// 监听路由变化，更新激活状态
router.afterEach((to, from) => {
  routePathsAndLabels.value.forEach((r) => {
    r.isActive = to.path === r.path;
  });
});

// 跳转页面
const goPage = (value) => {
  router.push(value.path);
  data.drawer = false;
};

//右击菜单
const clickByRight = (event) => {
  const e = event;
  e.preventDefault();
  menuLeft.value = e.pageX + "px"; // 菜单出现的位置距离左侧的距离
  menuTop.value = e.pageY + 20 + "px"; // 菜单出现的位置距离顶部的距离
  contextMenuVisible.value = true; // 显示菜单
};

// 全局点击事件处理函数
const handleClickOutside = (event) => {
  const menuElement = document.querySelector(".right-menu");
  if (menuElement && !menuElement.contains(event.target)) {
    contextMenuVisible.value = false;
  }
};

// 组件挂载时添加全局点击事件监听器
onMounted(() => {
  document.addEventListener("click", handleClickOutside);
  document.addEventListener("contextmenu", clickByRight);
});

// 组件卸载时移除全局点击事件监听器
onUnmounted(() => {
  document.removeEventListener("click", handleClickOutside);
  document.removeEventListener("contextmenu", clickByRight);
});
</script>

<template>
  <div class="c-layout h-full w-full">
    <ul
      class="right-menu"
      :style="{ left: menuLeft, top: menuTop }"
      v-show="contextMenuVisible"
    >
      <li>
        <el-button type="primary" @click="() => (data.drawer = true)" text
          >MENU</el-button
        >
      </li>
    </ul>
    <el-drawer v-model="data.drawer" title="MENU" direction="ltr">
      <div class="w-full h-full">
        <!-- 渲染路由列表 -->
        <ul class="w-full h-full">
          <li
            v-for="(route, index) in routePathsAndLabels"
            :key="index"
            class="w-full p-2 cursor-pointer rounded mb-1"
            :class="{ active: route.isActive }"
            @click="goPage(route)"
          >
            {{ route.label }} - {{ route.path }}
          </li>
        </ul>
      </div>
    </el-drawer>
    <RouterView></RouterView>
  </div>
</template>

<style lang="scss" scoped>
li:hover {
  background: var(--el-color-primary-light-9);
}

li {
  &.active {
    background: var(--el-color-primary-light-7);
    /* color: white; */
  }
}

.right-menu {
  display: flex;
  position: absolute;
  flex-direction: column;
  background-color: white;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  z-index: 999;
}
</style>
